package com.fenghongzhang.day012;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private EditText message;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String s = (String) msg.obj;
            message.setText(s);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        message = (EditText) findViewById(R.id.message);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_SMS},100);
        }

        MyObserver myObserver = new MyObserver(handler, this);
        ContentResolver contentResolver = getContentResolver();
        contentResolver.registerContentObserver(Telephony.Sms.CONTENT_URI,true,myObserver);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            ContentResolver contentResolver = getContentResolver();
            Cursor query = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
            if (query != null){
                while(query.moveToNext()){
                    String string = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
                    Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
                }
                //关闭游标
                query.close();
            }
        }else{

        }
    }
}
